package com.xxxx.config.security;

import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: yun2
 * @ClassName JwtTokenUtil
 * @description:
 * @author: ZhouBin
 * @create: 2022-05-21 19:51
 * @Version 1.0
 **/

public class JwtTokenUtil {
    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "created";
    @Value("${jwt.secret}")
    private String secret;
    //失效时间：
    @Value("${jwt.expiration}")
    private Long expiration;


    public  String generateToken(UserDetails userDetails) {
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);

    }

    public String getUserNameFormToken(String token) {
        String username;
        try {
            Claims claim = getClaimsFromToken(token);
            username = claim.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return claims;


    }

    public boolean validateToken(String token, UserDetails userDetails) {
        String username = getUserNameFormToken(token);
        return username.equals(userDetails.getUsername())&& !isTokenExpired(token);
    }

    private boolean isTokenExpired(String token) {
        Date expiraDate=getExpiredDateFromToken(token);
        return expiraDate.before(new Date());
    }

    private Date getExpiredDateFromToken(String token) {
        Claims claims=getClaimsFromToken(token);
        return claims.getExpiration();

    }
    public boolean canRefreash(String token){
        return !isTokenExpired(token);

    }
    public String refreshToken(String token){
        Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED,new Date());
        return generateToken(claims);
    }


    private  String generateToken(Map<String, Object> claims) {

        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generatExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();

    }

    private Date generatExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

}
